import React, { useContext } from 'react';
import { AppSetStateContext } from "../appState";
import { RobotProps } from "./Robot";
// react对HOC命名规范：HOC高阶函数使用with开头命名
export const withAddToCart = (ChildrenComponent: React.ComponentType<RobotProps>) => {
    return (props) => {
        // 当前的props是由App组件遍历下发的每一项item数据
        // console.log("props", props)
        const setState = useContext(AppSetStateContext);
        const addToCart = (id, name) => {
            if (setState) {
                // state是全局状体里的state对象 => defaultContextValue
                setState((state) => {
                    return {
                        ...state,
                        shoppingCart: {
                            items: [
                                // 展开之前存储的items数据
                                ...state.shoppingCart.items,
                                // 后面的{id, name}是新加入items的数据
                                {
                                    id,
                                    name
                                }
                            ],
                        }
                    }
                })
            }
        }
        return <ChildrenComponent {...props} addToCart={addToCart} />
    }
}
export const useAddToCart = () => {
    const setState = useContext(AppSetStateContext);
    const addToCart = (id, name) => {
        if (setState) {
            // state是全局状体里的state对象 => defaultContextValue
            setState((state) => {
                return {
                    ...state,
                    shoppingCart: {
                        items: [
                            // 展开之前存储的items数据
                            ...state.shoppingCart.items,
                            // 后面的{id, name}是新加入items的数据
                            {
                                id,
                                name
                            }
                        ],
                    }
                }
            })
        }
    }
    return addToCart;
}